import "reflect-metadata";
import { useKoaServer,useContainer } from "routing-controllers";
import { Container } from "typedi";
import { config } from "../config";
import { Logs } from "../utils/logs";
import { initPlugins } from "./init";
import path from "path";
import {authorizationChecker, currentUserChecker} from "../utils/auth";

export class App extends initPlugins{
  private Controller: Function[];
  private app: any;

  constructor () {
    super();
    // typedi 注入到 routing-controllers
    useContainer(Container);
    this.createKoa();
  }

  /**
   * 创建 koa 服务
   */
  createKoa() {
    this.app = useKoaServer(this.Koa2, {
      validation: true,
      classTransformer: true, // 是否开启类型转换，在获得参数的时候来决定参数形式
      controllers: [`${path.join(__dirname, '../controller/**/*{.js,.ts}')}`],
      authorizationChecker: authorizationChecker, // 配置身份校验
      currentUserChecker: currentUserChecker, // 获取当前用户
      routePrefix: '/api',
      cors: false, // 是否开启跨域请求
      middlewares: [], // 配置中间件
      interceptors: [], // 配置拦截器
    });
    this.run();
  }

  // 启动程序
  private run (): any {
    try {
      this.app.listen(config.port, () => console.log(config.banner.welcome()));
    } catch (e) {
      console.error(`❌ 启动出错：${e.message}`);
      Logs.ApplicationLogger().error(e);
    }
    this.errorCatch();
    // this.Page_404();
  }

  // 错误捕捉Unsupported type
  private errorCatch (): any {
    this.app.on('error', err => {
      console.error(`❌ 主程序捕捉到错误：${err.message}`);
      Logs.ApplicationLogger().error(err);
    });
  }
  
  /**
   * 捕捉到404的时候跳转到error错误页面
   * @constructor
   */
  private Page_404 () {
    this.app.use(async ctx => {
      if (ctx.response.status == 404) {
        ctx.redirect('/error');
      }
    })
  }

}